package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.entry.vo.CartItemVo;
import com.atguigu.gulimall.cart.entry.vo.CartVo;
import com.atguigu.gulimall.cart.entry.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.entry.vo.UserInfoTo;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    //购物车前缀
    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        //1.判断购物车是否有此产品，有修改数量，没有添加
        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)){
            //购物车无此商品
            //2.购物车没有此商品，添加新商品
            CartItemVo cartItemVo = new CartItemVo();

            //远程查询但前添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    //2。将查到的商品添加到购物车

                    cartItemVo.setSkuId(skuInfo.getSkuId());
                    cartItemVo.setCheck(true);
                    cartItemVo.setCount(num);
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfo.getPrice());
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                }
            }, executor);

            //远程查询销售属性
            CompletableFuture<Void> getAttrTask = CompletableFuture.runAsync(() -> {
                R attrR = productFeignService.getSkuSaleAttrValue(skuId);
                if (attrR.getCode() == 0){
                    List<String> data = attrR.getData(new TypeReference<List<String>>() {
                    });
                    cartItemVo.setSkuAttr(data);
                }
            }, executor);

            //等异步都完成
            CompletableFuture.allOf(getSkuInfoTask,getAttrTask).get();

            //json字符串保存到redis中
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),jsonString);

            return cartItemVo;
        }else {

            CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);

            //跟新保存到redis中
            String jsonString = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),jsonString);
            //修改数量
            return cartItemVo;
        }


    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);

        return cartItemVo;
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {

        CartVo cartVo = new CartVo();

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null){
            //登录了
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            BoundHashOperations ops = redisTemplate.boundHashOps(cartKey);
            //如果临时购物车的数据没有合并，需要先合并临时购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null && tempCartItems.size()>0){
                //临时购物车有数据，需要合并
                //如果购物车里有的购物项目，修改数量，没有的添加
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }

                //清除临时购物车数据
                this.clearCart(tempCartKey);
            }

            //合并后再来获取登录后的购物车
            //包括临时的和登录后的数据
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItemVos(cartItems);

        }else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItemVos(cartItems);
        }
        return cartVo;
    }

    /**
     * 获取当前用户的ops
     * @return
     */
    private BoundHashOperations getCartOps() {
        //获取用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1。
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            //用户已登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            //没有登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

//        redisTemplate.opsForHash().get(cartKey,"1");
        BoundHashOperations<String,Object,Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    /**
     * 获取指定购物车的购物项
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations ops = redisTemplate.boundHashOps(cartKey);
        List<String> values = ops.values();
        if (values != null && values.size() > 0){
            List<CartItemVo> collect = values.stream().map(value -> {
                String str = (String)value;
                CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());

            return collect;
        }
        return null;
    }


    //清空购物车
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {

        BoundHashOperations cartOps = getCartOps();

        CartItemVo cartItem = this.getCartItem(skuId);
        cartItem.setCheck(check == 1?true:false);

        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);

    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations cartOps = getCartOps();

        CartItemVo cartItem = this.getCartItem(skuId);
        cartItem.setCount(num);

        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations cartOps = getCartOps();

        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        //获取登录用户
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if (userInfoTo.getUserId() == null){
            //没有登录
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            //过滤被选中的购物项,再查出最新的价格
            List<CartItemVo> collect = cartItems.stream().filter(item -> {
                return item.getCheck();
            }).map(item->{
                //跟新最新价格
                R r = productFeignService.getPrice(item.getSkuId());
                if (r.getCode() == 0){
                    String price = (String) r.get("data");
                    item.setPrice(new BigDecimal(price));
                }

                return item;

            }).collect(Collectors.toList());

            return collect;
        }
    }
}
